import yaml
from bs4 import BeautifulSoup
from aiohttp import ClientSession
from datetime import datetime, timedelta
from dateutil import parser

format
class RssReader:

    __slots__ = ('url', 'ua', 'cfg')

    def __init__(self):
        self.cfg = yaml.safe_load(open('../config.yml', 'rb'))
        self.url = self.cfg['url']
        self.ua = self.cfg['ua']

    async def network_connector(self):
        async with ClientSession() as s:
            async with s.get(self.url) as r:
                # status = r.status
                page = await r.text()
                return page

    async def feed_reader(self):
        last_news = []
        p = await self.network_connector()
        raw_feed = BeautifulSoup(p, 'xml')
        feed = raw_feed.find_all('item')

        for i in feed:
            title = i.find('title').text
            link = i.find('link').text
            content = i.find('content:encoded').text
            raw_date = i.find('pubDate').text
            now_date = datetime.now()
            pub_date = parser.parse(raw_date).replace(tzinfo=None)
            date_delta = now_date - pub_date < timedelta(days=2)

            if date_delta:
                data = {'title': title,
                        'link': link,
                        'pub_date': str(pub_date),
                        'content': content}
                last_news.append(data)

        return last_news
